package com.example.home_model.details.customBehavior;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.customview.widget.ViewDragHelper;

import com.blankj.utilcode.util.ConvertUtils;

public class AnchorScrollBehavior extends CoordinatorLayout.Behavior<View> {
   private ViewDragHelper helper;
    private int height = 0;//滑动缩放的子View高度
    private View refView;//滑动缩放的子view
    public AnchorScrollBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
    }



    @Override
    public boolean onLayoutChild(@NonNull CoordinatorLayout parent, @NonNull View child, int layoutDirection) {
       if (helper == null) {

           helper = ViewDragHelper.create(parent, 1f, callback);
            refView = child;
            height = child.getMeasuredHeight();
       }
        return super.onLayoutChild(parent, child, layoutDirection);
    }

    @Override
    public boolean onTouchEvent(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull MotionEvent ev) {
       if (helper == null)
           return false;
       helper.processTouchEvent(ev);
        return true;
    }

    @Override
    public boolean onInterceptTouchEvent(@NonNull CoordinatorLayout parent, @NonNull View child, @NonNull MotionEvent ev) {
        if (helper == null)
            return super.onInterceptTouchEvent(parent, child, ev);

        return helper.shouldInterceptTouchEvent(ev);
    }
    private ViewDragHelper.Callback callback = new ViewDragHelper.Callback() {
        @Override
        public boolean tryCaptureView(@NonNull View child, int pointerId) {
            return true;
        }

        @Override
        public int clampViewPositionVertical(@NonNull View child, int top, int dy) {
            ViewGroup.LayoutParams layoutParams = child.getLayoutParams();
            if (layoutParams.height<0){
                layoutParams.height = height;
            }
            layoutParams.height +=dy;//当前高度+=每次移动的距离->
            if (layoutParams.height< ConvertUtils.dp2px(200)){
                layoutParams.height = ConvertUtils.dp2px(200);
            }
            if (layoutParams.height>height){
                layoutParams.height = height;
            }
            refView.setLayoutParams(layoutParams);
            return top;
        }
    };
}
